<template>
  <div id="myItemPosition">      <!--组合-->
    <div v-if="isLoading" class="loading">
      <img src="~assets/images/loading.gif"/>
      <div>加载中</div>
    </div>
    <div class="tips" v-if="dataList.length==0 && error!=''">{{error}}</div>

    <div class="cancel-group-item" v-for="group in dataList">
      <div class="x-comb-tip padder-sm">
        <div class="row m-n">
          <div class="col-sm-5 no-padder group-name" data-gid="id">
            <span class="text-md">{{group.group_name}}</span>
          </div>
          <div class="col-sm-4 text-center no-padder">
            <span class="text-xs">创建于{{group.create_date}}</span>
          </div>
          <div class="col-sm-3 text-right text-xs no-padder">
            仓位<span class="text-md">{{group.group_position}}%</span>
          </div>
        </div>
      </div>                                              <!--for loop-->
      <div class="pro-item" v-for="item in group.data">
        <div class="pro-item-lable">
          <div class="pro-item-tip bg-gray">
            <div class="pro-item-tip-type bg-df text-xs color-blue"
                 :class="{'color-blue':item.trade_type=='0','color-red':item.trade_type=='1'}">
              {{item.trade_type=='0'? '卖出': '买入'}}
            </div>
            <div class="pro-item-tip-time m-l-sm">
              <i class="iconfont text-xs color-9">&#xe606;</i>
              <span class="color-9 text-xs m-l-xs">
                   {{item.trade_time_str}}
                </span>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <div class="text-center padder-v padder-sm">
          <div class="hbox" @click.stop.prevent="clickBox(item)">
            <div class="col" stock-code="" market-cd="" style="width: 25%;text-align: left;">
              <div class="text-md">{{item.stock_name}}</div>
              <div class="text-xs color-9">{{item.stock_code}}</div>
            </div>
            <div class="col">
              <div class="positive">{{item.trade_price}}</div>
              <div class="text-xs color-9">{{item.commission}}委托</div>
            </div>
            <div class="col" style="width: 22%;">
              <div>{{item.trade_count}}</div>
              <div class="text-xs color-9">数量</div>
            </div>
            <div class="col" style="vertical-align: bottom;" v-if="isChecked == 1">
              <img src="../../../assets/images/yicheng.png" style="width: 57px;" class="m-t-n-sm">
            </div>
            <div class="col" style="vertical-align: bottom;" v-else>
              <img :src="imgUrl(item)" style='width: 57px;' class='m-t-n-sm'>
            </div>
            <div class="col text-right" v-if="item.entrust_status=='0'|| item.entrust_status=='3'"
                 @click.stop.prevent="cancelOrder(item,index)">
              <span class="cancel-order-btn">撤单</span>
            </div>
          </div>
        </div>
      </div>                                                                                   <!--stop loop-->
      <div class="bg-f5 pro-item-yy padder-sm text-xs color-9" v-if="group.reason1||group.reason2||group.reason3">
        调仓原因
        <i class="iconfont" :class="group.reason1.reasonIcon" style="font-size: inherit" v-if="group.reason1">{{group.reason1.reasonText}}</i>
        <i class="iconfont" :class="group.reason2.reasonIcon" style="font-size: inherit" v-if="group.reason2">{{group.reason2.reasonText}}</i>
        <i class="iconfont" :class="group.reason3.reasonIcon" style="font-size: inherit" v-if="group.reason3">{{group.reason3.reasonText}}</i>
      </div>
      <div class="bg-f5 pro-item-yy padder-sm text-xs color-9" v-else>
        暂无调仓原因
      </div>
    </div>
    <div v-if="!isLoading && dataList.length>0 && error==''" class="loading" >
      <img src="~assets/images/portfolio/niutou@2x.png"/>
      <div>已全部加载</div>
    </div>
  </div>
</template>
<script>
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'
  import CommonUtil from 'common/common.util'
  export default{
    data(){
      return {
        userCode: '',
        menuFlag: '2',
        isChecked: 0,
        dataList: [],
        isLoading:true,
        error: ''
      }
    },
    props: {
      checkStatus: {
        type: String
      }
    },
    created(){
      this.userCode = LocalDAO.getUserCode();   //取得用户ID
    },
    mounted: function () {
      this.isChecked = this.checkStatus
      this.getPositionData(2, this.isChecked);//  进入页面直接请求渲染数据
      this.$root.eventHub.$off('check')
      this.$root.eventHub.$on('check', (checkStatus)=> {                                   //   isChecked改变重新请求渲染数据
        this.isChecked = checkStatus;                                                   //  更新isChecked
      this.getPositionData(2, this.isChecked);
    })
    },
    methods: {
      getPositionData(entrust_type, isChecked){       // entrust_type 委托类型  1 个股 2组合
        this.error = ''
        this.isLoading = true
        var param = {
          "func_id": this.isChecked > 0 ? (this.isChecked == 1 ? '11117' : '11118') : '11119',    //  isChecked状态  0未选中  1 已成   2 可撤
          "client_id": this.userCode,
          "start": 0,
          "limit": 1000,
          "entrust_type": entrust_type
        };
        if (isChecked > 0) {                   //    有选中的CheckBox
          RemoteDAO.callJCL11117OR11118(param, (resp)=>{ //   当日已成委托11117  当日可撤单委托:11118   当日全部委托11119
            resp = resp || {};
          if (resp.error == 0) {
            this.error = ''
            var records = resp.data.body.records || []
            this.render(records)
          } else {
            this.isLoading = false;
            this.error = resp.data
          }
        })
        } else {
          RemoteDAO.callJCL11119(param, (resp)=> {     // 无选中的CheckBox     里面 处理到底是个股的还是组合的  肯定没有check都是全部的
            resp = resp || {};
          if (resp.error == 0) {
            this.error = ''
            var records = resp.data.body.records || []
            this.render(records, 1)
          } else {
            this.isLoading = false;
            this.error = resp.data
          }
        });
        }
      },
      render(records, show_type){                     //  show_type  可有可无
        RemoteDAO.callGT1008((response)=> {                             //   取得系统的时间
          var date_now = "";
        if (response.error == "0") {
          date_now = response.data.body.date;
        } else {
          date_now = CommonUtil.getTodayFormatDate();    //  get date_now   得到了系统的时间
        }
        this.groupByItem(this.formatData(records, show_type, date_now))
      })
      },
      formatData(list, show_type, date_now){                         //   进入块级作用域
        let formatList = [];
        for (var i = 0; i < list.length; i++) {
          var obj = list[i];
          var tempObj = {};
          tempObj.trade_no = obj.entrust_no;//委托标示
          tempObj.market_cd = obj.exchange_type;//市场标示
          tempObj.stock_code = obj.stock_code;//股票代码
          tempObj.stock_name = obj.stock_name;//股票名称
          var tradePrice = "", trade_count = "";
          var isCj = "";//1、显示委托价格 2、显示成交价格
          //撤单显示委托价额
          if (this.isChecked == '2') {
            tradePrice = obj.entrust_price;
            trade_count = obj.entrust_vol;
            isCj = "1";
          } else {
            if (show_type == "1") {
              if (obj.entrust_status == "2" || obj.entrust_status == "3") {
                tradePrice = obj.business_price;
                trade_count = obj.business_vol;
                isCj = "2";
              } else {
                tradePrice = obj.entrust_price;
                trade_count = obj.entrust_vol;
                isCj = "1";
              }
            } else {
              tradePrice = obj.business_price;
              trade_count = obj.business_vol;
              isCj = "2";
            }
          }
          tempObj.isCj = isCj
          tempObj.trade_price = tradePrice.toFixed(2);//
          tempObj.trade_count = trade_count;//
          tempObj.trade_type = CommonUtil.getBuyOrSellBuyType(obj.entrust_bs);//交易类型
          tempObj.commission = (obj.entrust_bs == 0 || obj.entrust_bs == 1) ? "限价" : "市价";
          tempObj.group_id = obj.entrust_typeid;//组合ID
          tempObj.group_name = obj.group_name;//组合名称
          tempObj.group_position = obj.group_position?obj.group_position:obj.position;//组合仓位
          tempObj.entrust_status = obj.entrust_status;//委托状态
          tempObj.create_date = CommonUtil.dateFormat(obj.create_date);
          tempObj.reason1 = CommonUtil.getReasonOption(obj.reason1);   //  返回的是一个对象
          tempObj.reason2 = CommonUtil.getReasonOption(obj.reason2);
          tempObj.reason3 = CommonUtil.getReasonOption(obj.reason3);
          tempObj.isReason = 1;//原因默认不为空
          if (tempObj.reason1 == null && tempObj.reason2 == null && tempObj.reason3 == null) {
            tempObj.isReason = 0;//说明原因全部为空
          }
          var date = ((this.isChecked == '2' || show_type == "1") ? obj.entrust_date : obj.business_date).toString();
          var time = ((this.isChecked == '2' || show_type == "1") ? obj.entrust_time : obj.business_time).toString();
          var date_str = "";
          if (date == date_now) {
            date_str = "今天 ";
          } else {
            date_str = CommonUtil.formatDatePoint(date) + " ";
          }
          time = time.length == 5 ? "0" + time : time;
          tempObj.trade_time_str = date_str + time.substring(0, 2) + ":" + time.substring(2, 4);
          formatList.push(tempObj);
        }
        if(formatList.length == 0){
          this.error = '暂无数据'
        }
        return formatList;
      },
      groupByItem(itemList){
//        this.$store.dispatch('setTip',{text:JSON.stringify(itemList)});
        var  len = itemList.length;
        var map = {}, dest = [];
        for (var i = 0; i < len; i++) {
          var obj = itemList[i];
          if (!map[obj.group_id]) {
            dest.push({
              group_id: obj.group_id,
              group_name: obj.group_name,
              group_position: obj.group_position != null ? obj.group_position.toFixed(2) : "-",//组合仓位
              create_date: obj.create_date,
              reason1: obj.reason1,
              reason2: obj.reason2,
              reason3: obj.reason3,
              data: [obj]
            });
            map[obj.group_id] = obj;
          } else {
            for (var j = 0; j < dest.length; j++) {
              var dj = dest[j];
              if (dj.group_id == obj.group_id) {
                if (!CommonUtil.isEmpty(obj.reason1)) {
                  dj.reason1 = obj.reason1;
                }
                if (!CommonUtil.isEmpty(obj.reason2)) {
                  dj.reason2 = obj.reason2;
                }
                if (!CommonUtil.isEmpty(obj.reason3)) {
                  dj.reason3 = obj.reason3;
                }
                dj.data.push(obj);
                break;
              }
            }
          }
        }
        this.dataList = dest;
        this.isLoading = false;
      },
      cancelOrder (item, index) {
        var param = {
          "client_id": this.userCode,
          "exchange_type": item.market_cd,
          "stock_code": item.stock_code,
          "entrust_no": item.trade_no
        };
        RemoteDAO.callJCL11115(param, (response) =>{
          if (response.error == "0") {
          var decryptData = JSON.parse(decrypt.json2(response.data));
          var body = decryptData.body || {};
          if (body.status == 0) {
            if(this.isChecked == 2){
              this.dataList.splice(index,1)
            }else{
              item.entrust_status = '1'
            }
            this.$store.dispatch('setTip', {text: "撤单成功"});
          } else {
            this.$store.dispatch('setTip', {text: body.describe != "" ? body.describe : "撤单失败"});
          }
        } else {
          this.$store.dispatch('setTip', {text: "撤单失败，" + response.data});
        }
      });
      },
      imgUrl(item){
        var url = '';
        if (item.entrust_status == '0') {
          url = require('../../../assets/images/order-status0.png')
        } else if (item.entrust_status == '1') {
          url = require('../../../assets/images/order-status1.png')
        } else if (item.entrust_status == '2') {
          url = require('../../../assets/images/order-status2.png')
        } else if (item.entrust_status == '3') {
          url = require('../../../assets/images/order-status3.png')
        } else if (item.entrust_status == '4') {
          url = require('../../../assets/images/order-status4.png')
        } else if (item.entrust_status == '5') {
          url = require('../../../assets/images/order-status5.png')
        }
        return url;
      },
      collapse(index, item){
        this.expandedIndex = index === this.expandedIndex ? '' : index;
        var userCode = this.dataList[index].client_id;
        if (this.expandedIndex != '' && (!this.subsChecked[userCode])) {
          this.checkSubscription(userCode, item);
        }
      },
      clickBox(item) {
        var stockCode = item.stock_code;
        var exchangeType = item.market_cd;

        var marketCode;
        if (exchangeType == "0") {
          marketCode = "SZ";
        } else if (exchangeType == "1") {
          marketCode = "SH";
        }

        RemoteDAO.callStockLive(marketCode + stockCode, "ordinary", "1", function () {

        });
      }
    }
  }
</script>
<style>
</style>
